package com.example.customviewprojdct.view.other

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import com.example.customviewprojdct.R
import com.example.customviewprojdct.databinding.ViewUniformTextBinding
import com.google.android.material.imageview.ShapeableImageView
import com.google.android.material.shape.ShapeAppearanceModel

/**
 * 群头像View展示
 * 规则：展示默认群头像，如果设置url为空，则展示群名前两个字；不为空则展示url图片。
 */
class IslandAvatarView @JvmOverloads constructor(
  context: Context, attrs: AttributeSet? = null, d: Int = 0
) : FrameLayout(context, attrs, d) {


  private val avatarImageView = ShapeableImageView(context)
  private var defaultTextView: TextView? = null

  init {
    avatarImageView.shapeAppearanceModel = ShapeAppearanceModel.Builder()
      .setAllCornerSizes(ShapeAppearanceModel.PILL)
      .build()
    avatarImageView.setImageResource(R.drawable.avatar)
    addView(avatarImageView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
  }

  override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
    Log.i("baize_", "onSizeChanged...")
    syncDefaultTextPadding()
  }

  private fun syncDefaultTextPadding() {
    if (defaultTextView?.parent == this) {
      val tvWidth = (width * 0.7).toInt()
      val tvPadding = (width * 0.2).toInt()
      Log.i("baize_", "syncDefaultTextPadding width:$width $tvWidth padding:$tvPadding")
      defaultTextView?.setPadding(tvPadding, tvPadding, tvPadding, tvPadding)
    }
  }

  fun setIslandInfo(url: String?, islandName: String) {
    if (url?.isNotBlank() == true) {
      avatarImageView.let {
        Log.i("baize_", "avatarImageView 展示url...$url $islandName")
        it.setImageResource(R.drawable.ic_launcher_foreground)
        it.visibility = View.VISIBLE
      }
      if (defaultTextView?.parent == this) {
        Log.i("baize_", "defaultTextView 隐藏...")
        defaultTextView?.visibility = GONE
      }
    } else {
      if (defaultTextView?.parent == this) {
        Log.i("baize_", "defaultTextView 展示...")
        defaultTextView?.visibility = VISIBLE
      } else {
        defaultTextView = ViewUniformTextBinding.inflate(LayoutInflater.from(context), this, true).root
        Log.i("baize_", "add default TextView...")
        syncDefaultTextPadding()
      }
      defaultTextView?.text = islandName
    }
  }

}